package com.hxrfid.common.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageUtils {

    public static byte[] generateQrCodeWithTopText(String content, String topText, int size) throws IOException {
        // 根据id生成二维码图片
        QrConfig config = new QrConfig(80, 80);
        // 设置边距，即二维码和背景之间的边距
        config.setMargin(3);
        BufferedImage qrImage = QrCodeUtil.generate(content, QrConfig.create());
        // 创建新图像，高度增加用于显示文字
        int margin = 20;
        int imageWidth = size + 2 * margin; // 增加左右边距防止裁剪
        int imageHeight = size + 40 + 2 * margin; // 增加上下边距
        BufferedImage combinedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = combinedImage.createGraphics();
        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 绘制顶部文字，居中显示
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("微软雅黑", Font.BOLD, 16));
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(topText);
        int textX = (imageWidth - textWidth) / 2;
        g2d.drawString(topText, textX, margin + 20); // 留出上边距
        // 绘制二维码，居中于下方区域
        g2d.drawImage(qrImage, margin, margin + 40, size, size, null);
        g2d.dispose();
        // 输出为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(combinedImage, "PNG", baos);
        return baos.toByteArray();
    }

    /**
     * 将BufferedImage转换为Base64编码的字符串
     *
     * @param qrCodeValue 二维码的值
     * @return Base64编码的字符串
     */
    public static String bufferedImageToBase64(String qrCodeValue) {
        // 根据id生成二维码图片
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，即二维码和背景之间的边距
        config.setMargin(3);
        BufferedImage generate = QrCodeUtil.generate(qrCodeValue, QrConfig.create());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(generate, "png", baos);
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (IOException e) {
            throw new RuntimeException("二维码图片转Base64失败", e);
        }
    }
}
